<?php
class PrefsManager 
{
	var $dbm;
	var $sess;

	function PrefsManager ( & $dbm, & $sess )
	{
		$this->dbm = & $dbm;
		$this->sess = & $sess;
	}

	function & read_prefs ( $mod_name, & $prefs, $uid = 0 )
	{
		// Read default prefs (uid: 0)
		$res = $this->_retrieve_user ( $mod_name, 0 );	

                foreach ( $prefs as $key => $val )
                        if ( ! array_key_exists ( $key, $res ) ) $res [ $key ] = $val [ 'default' ];

		// Read user prefs (real [or resolved] $uid )
		$usr = $this->read_user ( $mod_name, $uid );

		// Join $res and $usr arrays
		foreach ( $res as $key => $val )
			if ( ! array_key_exists ( $key, $usr ) ) $usr [ $key ] = $val;

		// Return joined prefs
		return $usr;
	}
	
	function & read_user ( $mod_name, $uid = 0 )
	{
		if ( ! $uid ) $uid = $this->sess->get ( "uid" );
		if ( ! $uid ) $uid = "0";

		$vals = $this->_retrieve_user ( $mod_name, $uid );
		return $vals;
	}

	function & _retrieve_user ( $mod_name, $uid )
	{
		$sql = "SELECT prefs FROM user_pref WHERE uid=$uid AND module_name='$mod_name'";
		$vals = & $this->_retrieve_prefs ( $sql );

		return $vals;
	}

	function write_user ( & $prefs, $mod_name, $uid = 0 )
	{
		if ( ! $uid ) $uid = $this->sess->get ( "uid" );
		if ( ! $uid ) $uid = "0";

		$this->_write_prefs ( & $prefs, $mod_name,  $uid );
	}

	function & _retrieve_prefs ( $sql )
	{ 
		$v = & $this->dbm->single_row ( $sql );

		if ( $v )
			$vals = unserialize ( $v [ 'prefs' ] );
		else 
			$vals = array ();

		return $vals;
	}

	function & _write_prefs ( & $prefs, $mod_name, $uid )
	{
		$p = addslashes ( serialize ( $prefs ) );

		$sql = "REPLACE INTO user_pref ( uid, module_name, prefs ) VALUES ( $uid, '$mod_name', '$p' )";
		$this->dbm->exec ( $sql );
	}
}
?>
